package cn.example.databaseoperationdemo;

import static android.widget.Toast.LENGTH_SHORT;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.sqlite.SQLiteCantOpenDatabaseException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.litepal.LitePal;

public class MainActivity extends AppCompatActivity {

    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        LitePal.getDatabase();// 创建数据库

        etUsername = this.findViewById(R.id.username);
        etPassword = this.findViewById(R.id.password);
        btnLogin = this.findViewById(R.id.login);
        btnRegister = this.findViewById(R.id.register);

        // 登录
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                try{
                    User loginUser = LitePal.where("username = ? and password = ?", username, password).findFirst(User.class);
                    if(null != loginUser){
                        Toast.makeText(v.getContext(),"登录成功", LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, ManagerActivity.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(v.getContext(), "登录失败", LENGTH_SHORT).show();
                    }
                }catch (SQLiteCantOpenDatabaseException e){
                    Toast.makeText(v.getContext(), "异常 " + e.getMessage(), LENGTH_SHORT).show();
                }
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到登录页面
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
                Toast.makeText(v.getContext(), "前往注册", LENGTH_SHORT).show();
            }
        });

    }
}